<template>
  <BasicDrawer
    :title="title"
    :width="width"
    v-bind="$attrs"
    @ok="methods.handleSubmit"
    @register="registerModel"
    :useWrapper="true"
    destroyOnClose
  >
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="1" tab="基础资料" force-render>
        <BasicForm @register="registerForm" />
      </a-tab-pane>
      <a-tab-pane key="2" tab="联系资料" force-render>
        <BasicTable @register="registerTable">
          <template #headerCell="{ column }">
            <template v-if="column.key == 'action'">
              <a-space>
                <div>操作</div>
                <PlusCircleFilled
                  class="cursor-pointer"
                  :style="{ color: '#b6b7b9' }"
                  @click="addCustomer"
                />
              </a-space>
            </template>
          </template>
          <template #bodyCell="data">
            <template v-if="data.column?.key == 'action'">
              <TableAction :actions="tmethods.getTableAction(data.record)" />
            </template>
            <slot name="column" v-bind="data || {}"></slot>
          </template>
        </BasicTable>
      </a-tab-pane>
    </a-tabs>
  </BasicDrawer>
  <CustomerModel @register="registerLayer" @success="accpteData" />
</template>
<script setup lang="ts">
  import ApiV1 from '@/views/common/operate/ApiV1';
  import BasicForm from '@/components/Form/src/BasicForm.vue';
  import BasicDrawer from '@/components/Drawer/src/BasicDrawer.vue';
  import { useAutoAdaptWidth } from '@/hooks/system/useAutoAdapt';
  import gloabComponentConfig from '@/settings/gloabComponentConfig';
  import { Tabs as ATabs, TabPane as ATabPane, Space as ASpace } from 'ant-design-vue';
  import { ref } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { useCustomerHandleListColumns } from '@/views/system/basic/contacts/customer.data';
  import { PlusCircleFilled } from '@ant-design/icons-vue';
  import CustomerModel from '@/views/system/basic/contacts/customerModel.vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { isNil, findIndex, forEach } from 'lodash-es';
  import { buildUUID } from '@/utils/uuid';
  import { useSupplierUpdateSchemaForm } from '@/api/http/system/basic/supplier/supplier.data';
  import {
    apiGetSupplierDetailsPath,
    apiPostSupplierAdd,
    apiPostSupplierUpdatePath,
  } from '@/api/http/system/basic/supplier/supplier.api';

  const { createMessage } = useMessage();
  const { width } = useAutoAdaptWidth(gloabComponentConfig.adaptiveWidth);
  const emit = defineEmits(['success', 'register']);
  const { registerForm, registerModel, methods, title } = ApiV1.useHandle(emit, {
    formProps: { schemas: useSupplierUpdateSchemaForm(), baseColProps: { span: 12 } },
    title: '供应商信息',
    details: apiGetSupplierDetailsPath,
    saveFn: apiPostSupplierAdd,
    updateFn: apiPostSupplierUpdatePath,
    mode: 'drawer',
    beforeSubmit: async (values) => {
      values['contacts'] = tableMethods.getDataSource();
      return values;
    },
    afterQuery: async (res) => {
      const data = res['contacts'];
      forEach(data, (item) => {
        item['uuid'] = buildUUID();
      });
      tableMethods.setTableData(data);
      activeKey.value = '1';
    },
  });
  // 联系资料
  const activeKey = ref('1');
  const datasourceRef = ref([]);
  const {
    registerTable,
    registerLayer,
    userInnerMethod,
    methods: tmethods,
    tableMethods,
  } = ApiV1.useList({
    tableProps: {
      columns: useCustomerHandleListColumns(),
      useSearchForm: false,
      dataSource: datasourceRef.value,
      showTableSetting: false,
      rowKey: 'uuid',
    },
    editActionItem: (record) => {
      return {
        onClick: () => {
          record['isUpdate'] = true;
          userInnerMethod.openModal(true, record);
        },
      };
    },
    delActionItem: (record) => {
      return {
        auth: 'system:basic:supplier:delete',
        popConfirm: {
          placement: 'topRight',
          title: '是否确认删除',
          confirm: () => {
            tableMethods.deleteTableDataRecord(record['uuid']);
          },
        },
      };
    },
    mode: 'model',
  });
  const addCustomer = () => {
    userInnerMethod.setModalProps({ canFullscreen: false });
    userInnerMethod.openModal(true);
  };
  const accpteData = (e) => {
    if (e['primary'] == 1) {
      const datasource = tableMethods.getDataSource();
      const index = findIndex(datasource, (item) => {
        return item.primary == 1;
      });
      if (index !== -1) {
        const arr = datasource;
        arr[index].primary = 0;
        tableMethods.updateTableDataRecord(arr[index]['uuid'], arr[index]);
      }
    }

    if (isNil(e['uuid'])) {
      e['uuid'] = buildUUID();
      tableMethods.insertTableDataRecord(e);
    } else {
      tableMethods.updateTableDataRecord(e['uuid'], e);
    }
    createMessage.success('联系资料操作成功,保存后生效');
  };
</script>
